﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PetaPoco;


namespace SellerCube.Service.Utilities
{
    public abstract class BaseService<T> where T:new()
    {
        private const string _PK = "_PK_";

        // cache duration(minutes)
        protected const int TWENTY_FOUR_HOURS = 1440;

        public BaseService()
        {
        }

        public BaseService(string cacheKeyName)
        {
            PKCacheKeyName = cacheKeyName + _PK;
        }

        public string PKCacheKeyName
        {
            get;
            set;
        }

        T _dao;

        public T Dao
        {
            get
            {
                if (_dao == null) _dao = new T();
                return _dao;
            }
            set { _dao = value; }
        }

        /// <summary>
        /// 队列数据发送
        /// </summary>
        /// <param name="data">被发送数据</param>
        /// <param name="action">执行发送的事件</param>
        /// <param name="originKey">发送数据的主键</param>
        /// <param name="category">类型</param>
        /// <param name="subCategory">子类型</param>
        /// <author>柯广强 2015/8/17</author>
        public void Send(object data, Action<TransmitData<string>> action, string originKey, TransmitCategory category, TransmitSubCategory subCategory)
        {
            return;

            #region obselete
            //var sendData = new SCB.Equeue.Upload.Contract.Models.TransmitData<string>
            //{
            //    Body = JsonHelper.SerializeObject(data),
            //    CreateTime = DateTime.Now,
            //    TransmitCategory = category,
            //    TransmitSubCategory = subCategory,
            //    OriginBatchGuid = SGUID.GenerateComb().ToString("N"),
            //    ListenedDate = DateTime.Now,
            //    OriginKey = originKey,
            //    Sender = ConfigConstant.EqueueKey,
            //    Title = ""
            //};


            ////保存文件位置
            //var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ("Uploads/EqueueSends"), category.ToString(), DateTime.Now.ToString("yyyyMMdd"));
            //var fileName = string.Format("{0}-{1}.txt", originKey, sendData.OriginBatchGuid);
            //var fileLocation = System.IO.Path.Combine(path, fileName);

            //bool success = false;
            //string failureMessage = null;
            //int runTimes = 3;
            //short uploadCount = 0;
            //try
            //{
            //    //保存文件
            //    FileHelper.Save(JsonHelper.SerializeObject(sendData), path, fileName);

            //    if (ConfigConstant.RunUploadEqueues.Value)
            //    {
            //        var res = SendByTimes(action, sendData, runTimes, out uploadCount);
            //        if (!res.IsSuccess)
            //        {
            //            failureMessage = res.Message;
            //        }
            //        success = res.IsSuccess;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    success = false;
            //    failureMessage = ex.Message;
            //    LogHelper.Error("队列发送", ex);
            //}
            //new EqueueSendDAO().Insert(new EqueueSend
            //{
            //    FileLocation = fileLocation,
            //    CreatedDate = sendData.CreateTime,
            //    Sender = sendData.Sender,
            //    OriginKey = sendData.OriginKey,
            //    OriginBatchGuid = sendData.OriginBatchGuid,
            //    Success = success,
            //    UploadCount = uploadCount,
            //    TransmitCategory = sendData.TransmitCategory,
            //    TransmitSubCategory = sendData.TransmitSubCategory,
            //    FailureMessage = string.IsNullOrEmpty(failureMessage) ? "" : (failureMessage.Length > 300 ? failureMessage.Substring(0, 300) : failureMessage)
            //}); 
            #endregion
        }

        /// <summary>
        /// 重新发送
        /// </summary>
        /// <param name="action"></param>
        /// <param name="sendData"></param>
        /// <returns></returns>
        public ResultSet ReSend(Action<TransmitData<string>> action, TransmitData<string> sendData)
        {
            int runTimes = 1;
            short count;
            return SendByTimes(action, sendData, runTimes, out count);
        }

        /// <summary>
        /// 执行委托(成功或失败runTimes次)
        /// </summary>
        /// <param name="action">委托</param>
        /// <param name="sendData">内容</param>
        /// <param name="runTimes">执行次数</param>
        /// <returns></returns>
        private ResultSet SendByTimes(Action<TransmitData<string>> action, TransmitData<string> sendData, int runTimes, out short times)
        {
            times = 1;
        ReTry:
            try
            {
                action(sendData);
            }
            catch (Exception ex)
            {
             //   LogHelper.Error(string.Format("队列发送——{0}", sendData.OriginBatchGuid), ex);

                if (times < runTimes)
                {
                    times++;
                    //设定次数内，继续发送，直至成功或超过次数
                    goto ReTry;
                }
                //超过设定次数后，返回结果
                return new ResultSet(ex.Message);
            }
            //返回成功结果
            return new ResultSet();
        }

        /// <summary>
        /// 执行队列处理和保存处理结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action">执行事件</param>
        /// <param name="transmit">提交数据</param>
        /// <param name="fileLocation">文件保存位置</param>
        /// <returns>成功或失败信息</returns>
        /// <author>柯广强 2015/5/25</author>
    }
}
